package com.demo.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class CollUtil {

    public static <T> boolean isEmpty(Collection<T> list) {
        return list == null || list.isEmpty();
    }

    public static <T> boolean isNotEmpty(Collection<T> list) {
        return !isEmpty(list);
    }

    public static <T> T getLast(List<T> list) {
        if (isEmpty(list)) {
            return null;
        }
        return list.get(list.size() - 1);
    }

    public static <T> T getOrNull(List<T> list, int index) {
        if (isEmpty(list)) {
            return null;
        }
        if (index >= list.size()) {
            return null;
        }
        return list.get(index);
    }

    public static <T> T getOrLast(List<T> list, int index) {
        if (isEmpty(list)) {
            return null;
        }
        if (index >= list.size()) {
            return getLast(list);
        }
        return list.get(index);
    }

    @SafeVarargs
    public static <T> ArrayList<T> concat(Collection<T> ...lists) {
        ArrayList<T> results = new ArrayList<>();
        for (Collection<T> list : lists) {
            if (isEmpty(list)) {
                continue;
            }
            results.addAll(list);
        }
        return results;
    }

    @SafeVarargs
    public static <T> ArrayList<T> push(Collection<T> list, T ...items) {
        ArrayList<T> results = new ArrayList<>();
        if (isNotEmpty(list)) {
            results.addAll(list);
        }
        results.addAll(Arrays.asList(items));
        return results;
    }

}
